package cn.dyp.com.getsensordata.activity;

import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

import cn.dyp.com.getsensordata.R;
import cn.dyp.com.getsensordata.ClientApp;
import cn.dyp.com.getsensordata.dialog.IpSetDialog;
import cn.dyp.com.getsensordata.fragment.ControlFragment;
import cn.dyp.com.getsensordata.fragment.EnvirFragment;
import cn.dyp.com.getsensordata.fragment.HistoryFragment;
import cn.dyp.com.getsensordata.fragment.SettingFragment;
import cn.dyp.com.getsensordata.request.BaseRequest;
import cn.dyp.com.getsensordata.request.GetConfigRequest;
import cn.dyp.com.getsensordata.request.GetSensorRequest;
import cn.dyp.com.getsensordata.request.RequestThread;

/**
 * 控制界面切换的Activity
 * 在MainLayout的基础上添加网络请求功能
 * @author asus
 */

public class MainActivity extends FragmentActivity {
	private FragmentTabHost mTabHost;
	private TextView mTitleTV;
	private String[] mTagStrings;
	private GetConfigRequest mConfigRequest;
	private RequestThread mConfigThread, mSensorThread;
	private ClientApp mApp;
	private GetSensorRequest mSensorRequest;
	private int[] images;
	private Class<?>[] fragments;
	private Thread mThread;
	private boolean flag = true;

	public interface OnUpDate {
		void upDate();
	}

	private OnUpDate mUpDate;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow();
		// 设置App全屏显示
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.activity_main);
		mApp = (ClientApp) getApplication();
		setRequest();
		iniData();
		initView();
		addTabs();
		setListener();
		showDialog();
	}

	/**
	 * 显示Ip设置Dialog
	 * 
	 */
	private void showDialog() {
		IpSetDialog dialog = new IpSetDialog(this);
		dialog.setShow(new IpSetDialog.OnAfterShow() {

			@Override
			public void onEnvent() {
				mThread = new Thread(new Runnable() {

					@Override
					public void run() {
						while (flag) {
							setGetConfigThread();
							try {
								Thread.sleep(500);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
				});
				mThread.start();
				setGetSenosorThread();
			}
		});
		dialog.show(getSupportFragmentManager(), "dialog");
	}

	/**
	 * 设置数据更新的监听器
	 * 
	 * @param upDate
	 *            监听器
	 */
	public void setUpDate(OnUpDate upDate) {
		this.mUpDate = upDate;
	}

	/**
	 * 设置、启动获取传感器阀值的线程
	 * 
	 */
	private void setGetConfigThread() {
		mConfigThread = new RequestThread(this, mApp.getHandler());
		mConfigThread.setRequest(mConfigRequest);
		mConfigThread.start();
	}

	/**
	 * 设置、启动获取传感器当前值的线程
	 * 
	 */
	private void setGetSenosorThread() {
		mSensorThread = new RequestThread(this, mApp.getHandler());
		mSensorThread.setLoop(true, 1500);
		mSensorRequest = new GetSensorRequest("");
		mSensorRequest.setSensorValue(mApp.getCurSensorValue());
		mSensorRequest
				.setOnResponseEventListener(new BaseRequest.OnResponseEventListener() {

					@Override
					public void onResponse(BaseRequest request,
							BaseRequest.RequestResult result) {
						mUpDate.upDate();
					}
				});
		mSensorThread.setRequest(mSensorRequest);
		mSensorThread.start();
	}

	/**
	 * 设置阀值请求对象
	 * 
	 */
	private void setRequest() {
		mConfigRequest = new GetConfigRequest("");
		mConfigRequest.setSensorConfig(mApp.getSensorConfig());
		mConfigRequest
				.setOnResponseEventListener(new BaseRequest.OnResponseEventListener() {

					@Override
					public void onResponse(BaseRequest request,
							BaseRequest.RequestResult result) {
						if (mConfigRequest.isSuccess()) {
							mThread.interrupt();
							flag = false;
						}
					}
				});
	}

	/**
	 * 初始化数据
	 */
	private void iniData() {
		// 获取Tag数组
		mTagStrings = getResources().getStringArray(R.array.tag);
		// 创建Tag图片数组
		images = new int[] { R.drawable.chart_icon, R.drawable.history_icon,
				R.drawable.control_icon, R.drawable.setting_icon };
		// 创建Fragment数组
		fragments = new Class<?>[] { EnvirFragment.class,
				HistoryFragment.class, ControlFragment.class,
				SettingFragment.class };

	}

	/**
	 * 初始化控件
	 */
	private void initView() {
		mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

		mTitleTV = (TextView) findViewById(R.id.title_tv);
		mTitleTV.setText(mTagStrings[0]);
	}

	/**
	 * 添加视图和指示器
	 */
	private void addTabs() {
		for (int i = 0; i < mTagStrings.length; i++) {
			TabSpec tag = mTabHost.newTabSpec(mTagStrings[i]).setIndicator(
					getTabItemView(i));
			mTabHost.addTab(tag, fragments[i], null);
			mTabHost.getTabWidget().getChildAt(i)
					.setBackgroundResource(R.drawable.bg);
		}
	}

	/**
	 * 添加监听器
	 */
	private void setListener() {
		TabHost.OnTabChangeListener mListener = new TabHost.OnTabChangeListener() {

			@Override
			public void onTabChanged(String tabId) {
				if (tabId.equalsIgnoreCase(mTagStrings[0])) {
					mTitleTV.setText(mTagStrings[0]);
				} else if (tabId.equalsIgnoreCase(mTagStrings[1])) {
					mTitleTV.setText(mTagStrings[1]);
				} else if (tabId.equalsIgnoreCase(mTagStrings[2])) {
					mTitleTV.setText(mTagStrings[2]);
				} else {
					mTitleTV.setText(mTagStrings[3]);
				}
			}
		};
		mTabHost.setOnTabChangedListener(mListener);
	}

	/**
	 * 给Tab按钮设置图标和文字
	 */
	private View getTabItemView(int index) {
		View view = LayoutInflater.from(this).inflate(R.layout.tab_layout,
				mTabHost.getTabWidget(), false);
		TextView textView = (TextView) view.findViewById(R.id.textview);
		textView.setText(mTagStrings[index]);
		BitmapDrawable drawable = (BitmapDrawable) getResources().getDrawable(
				images[index]);
		drawable.setBounds(0, 0, drawable.getMinimumWidth(),
				drawable.getMinimumHeight());
		textView.setCompoundDrawables(null, drawable, null, null);
		textView.setTextColor(Color.BLACK);
		return view;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mThread.interrupt();
		flag = false;
		mSensorThread.stopRequestThread();
	}
}
